// 进程监控渲染器
class ProcessRenderer {
    constructor() {
        // 工具方法
        this.escapeHtml = this.escapeHtml.bind(this);
    }

    // 渲染连接表格（分页模式）
    renderConnections(connections) {
        console.log('渲染连接数据:', connections);
        const tbody = document.getElementById('connections-tbody');
        
        if (connections.length === 0) {
            tbody.innerHTML = '<tr><td colspan="11" class="loading">无连接数据</td></tr>';
            return;
        }

        tbody.innerHTML = connections.map(conn => `
            <tr>
                <td>${this.escapeHtml(conn.process_name || 'Unknown')}</td>
                <td>${conn.pid}</td>
                <td><span class="protocol-badge protocol-${conn.protocol.toLowerCase()}">${conn.protocol}</span></td>
                <td>${conn.local_addr}:${conn.local_port}</td>
                <td>${conn.remote_addr}:${conn.remote_port}</td>
                <td><span class="status-badge status-${conn.status.toLowerCase().replace('-', '')}">${conn.status}</span></td>
                <td>${conn.bytes_sent_text || '0 B'}</td>
                <td>${conn.bytes_recv_text || '0 B'}</td>
                <td>${conn.speed_up_text || '0 B/s'}</td>
                <td>${conn.speed_down_text || '0 B/s'}</td>
                <td>
                    <button class="action-btn view" onclick="processMonitor.showProcessDetail(${conn.pid})">查看</button>
                </td>
            </tr>
        `).join('');
    }

    // 渲染进程表格（分页模式）
    renderProcesses(processes) {
        console.log('渲染进程数据:', processes);
        const tbody = document.getElementById('processes-tbody');
        
        if (processes.length === 0) {
            tbody.innerHTML = '<tr><td colspan="10" class="loading">无进程数据</td></tr>';
            return;
        }

        tbody.innerHTML = processes.map(process => `
            <tr>
                <td>${this.escapeHtml(process.process_name || 'Unknown')}</td>
                <td>${process.pid}</td>
                <td>${process.username || 'N/A'}</td>
                <td>${process.total_connections || 0}</td>
                <td>${process.active_tcp || 0}</td>
                <td>${process.active_udp || 0}</td>
                <td>${(process.listening_ports || []).join(', ') || '无'}</td>
                <td>${process.total_sent_text || '0 B'}</td>
                <td>${process.total_recv_text || '0 B'}</td>
                <td>${process.speed_up_text || '0 B/s'}</td>
                <td>${process.speed_down_text || '0 B/s'}</td>
                <td>
                    <button class="action-btn view" onclick="processMonitor.showProcessDetail(${process.pid})">详情</button>
                </td>
            </tr>
        `).join('');
    }

    // 渲染进程详情模态框
    renderProcessDetail(result) {
        if (!result) {
            console.error('获取进程详情失败: 进程不存在');
            return;
        }
        
        const process = result.process;
        const connections = result.connections || [];
        
        const content = document.getElementById('process-detail-content');
        content.innerHTML = `
            <div class="process-detail">
                <h4>基本信息</h4>
                <dl>
                    <dt>进程名:</dt>
                    <dd>${this.escapeHtml(process.process_name || 'Unknown')}</dd>
                    <dt>PID:</dt>
                    <dd>${process.pid}</dd>
                    <dt>用户:</dt>
                    <dd>${process.username || 'N/A'}</dd>
                    <dt>可执行文件:</dt>
                    <dd>${process.executable || 'N/A'}</dd>
                    <dt>启动时间:</dt>
                    <dd>${process.start_time || 'N/A'}</dd>
                    <dt>最后更新:</dt>
                    <dd>${process.last_update || 'N/A'}</dd>
                </dl>

                <h4>网络统计</h4>
                <dl>
                    <dt>总连接数:</dt>
                    <dd>${process.total_connections || 0}</dd>
                    <dt>TCP连接:</dt>
                    <dd>${process.active_tcp || 0}</dd>
                    <dt>UDP连接:</dt>
                    <dd>${process.active_udp || 0}</dd>
                    <dt>监听端口:</dt>
                    <dd>${(process.listening_ports || []).join(', ') || '无'}</dd>
                    <dt>总发送:</dt>
                    <dd>${process.total_sent_text || '0 B'}</dd>
                    <dt>总接收:</dt>
                    <dd>${process.total_recv_text || '0 B'}</dd>
                    <dt>上传速率:</dt>
                    <dd>${process.speed_up_text || '0 B/s'}</dd>
                    <dt>下载速率:</dt>
                    <dd>${process.speed_down_text || '0 B/s'}</dd>
                    <dt>状态:</dt>
                    <dd>${process.is_alive ? '运行中' : '已退出'}</dd>
                </dl>

                <h4>活跃连接 (${connections.length})</h4>
                <div class="connections-list">
                    ${connections.map(conn => `
                        <div class="connection-item">
                            ${conn.protocol} ${conn.local_addr}:${conn.local_port} → ${conn.remote_addr}:${conn.remote_port} (${conn.status})<br>
                            <small>
                                发送: ${conn.bytes_sent_text || '0 B'} | 
                                接收: ${conn.bytes_recv_text || '0 B'} | 
                                上传速率: ${conn.speed_up_text || '0 B/s'} | 
                                下载速率: ${conn.speed_down_text || '0 B/s'} | 
                                创建时间: ${conn.created_at || 'N/A'} | 
                                最后活跃: ${conn.last_seen || 'N/A'}
                            </small>
                        </div>
                    `).join('')}
                    ${connections.length === 0 ? '<div class="no-connections">无活跃连接</div>' : ''}
                </div>
            </div>
        `;

        document.getElementById('process-detail-modal').style.display = 'block';
    }

    // 更新统计卡片
    updateSummaryCards(summary) {
        if (summary) {
            document.getElementById('total-connections').textContent = summary.total_connections || 0;
            document.getElementById('tcp-connections').textContent = summary.total_tcp_connections || 0;
            document.getElementById('udp-connections').textContent = summary.total_udp_connections || 0;
            document.getElementById('monitored-processes').textContent = summary.active_processes || 0;
            
            // 使用格式化的速率字符串
            document.getElementById('total-upload-speed').textContent = `${(summary.total_speed_up_mbps || 0).toFixed(2)} Mbps`;
            document.getElementById('total-download-speed').textContent = `${(summary.total_speed_down_mbps || 0).toFixed(2)} Mbps`;
        }
    }

    // 从进程数据中计算统计信息并更新卡片
    updateSummaryCardsFromProcesses(processes) {
        const summary = {
            total_processes: processes.length,
            active_processes: processes.filter(p => p.is_alive).length,
            total_connections: processes.reduce((sum, p) => sum + (p.total_connections || 0), 0),
            total_tcp_connections: processes.reduce((sum, p) => sum + (p.active_tcp || 0), 0),
            total_udp_connections: processes.reduce((sum, p) => sum + (p.active_udp || 0), 0),
            total_speed_up_mbps: processes.reduce((sum, p) => sum + (p.speed_up || 0), 0),
            total_speed_down_mbps: processes.reduce((sum, p) => sum + (p.speed_down || 0), 0)
        };
        
        console.log('从进程数据计算的统计:', summary);
        this.updateSummaryCards(summary);
    }

    // HTML转义工具方法
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 创建全局实例
window.processRenderer = new ProcessRenderer();